package glassline.mock;

import java.util.Timer;
import java.util.TimerTask;

import transducer.TChannel;
import transducer.TEvent;
import transducer.TReceiver;
import transducer.Transducer;

public class MockGUI implements TReceiver {
	
	Transducer transducer;
	Timer timer = new Timer();
	long workTime = 700;
	long popupMovementTime = 300;
	
	/**
	 * Creates MockGUI with given transducer and registers MockGUI with it.
	 * Uses default workTime, the time it takes for a workStation to do its thing, as 700 ms
	 * Uses default popupMovementTime, time it takes for a popup to go up or down, as 300 ms
	 * @param t transducer to be used
	 */
	public MockGUI(Transducer t) {
		transducer = t;
		transducer.register(this, TChannel.POPUP);
		transducer.register(this, TChannel.WORKSTATION);
	}
	
	/**
	 * Creates MockGUI with given transducer and registers MockGUI with it.
	 * @param t transducer to be used
	 * @param workTime time it takes for a workStation to work
	 * @param popupMovementTime time it takes for a popup to move up or down
	 */
	public MockGUI(Transducer t, long workTime, long popupMovementTime) {
		transducer = t;
		transducer.register(this, TChannel.POPUP);
		transducer.register(this, TChannel.WORKSTATION);
		this.workTime = workTime;
		this.popupMovementTime = popupMovementTime;
	}
	
	public synchronized void eventFired(TChannel channel, TEvent event, Object[] args) {
		//TODO: WARNING: having this method synchronized, and firing events on the same channel we receive on may cause deadlock
		final Object[] id = args;
		if (channel == TChannel.WORKSTATION) {
			if (event == TEvent.WORKSTATION_ANIMATE_START) {
				timer.schedule(new TimerTask() {
					public void run() {
						transducer.fireEvent(TChannel.WORKSTATION, TEvent.WORKSTATION_ANIMATE_DONE, id);
					}
				}, workTime);
			}
		}
		if (channel == TChannel.POPUP) {
			if (event == TEvent.POPUP_GO_UP) {
				timer.schedule(new TimerTask() {
					public void run() {
						transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_NOW_UP, id);
					}
				}, popupMovementTime);
			}
			if (event == TEvent.POPUP_GO_DOWN) {
				timer.schedule(new TimerTask() {
					public void run() {
						transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_NOW_DOWN, id);
					}
				}, popupMovementTime);
			}
		}

	}

}
